<script setup>
// 引入发送请求的接口
import { userRegisterService, userLogin } from '@/api/user.js'
import { User, Lock } from '@element-plus/icons-vue'
// import { rules } from 'eslint-plugin-vue'
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
// 引入pinia存储用户数据
import { useUserStore } from '@/stores/index'
// 页面跳转router.push
import { useRouter } from 'vue-router'
const router = useRouter()
// 页面切换
const isRegister = ref(true)
// 定义一个form来做预校验
const form = ref()
//配置规则
const rulesForm = ref({
  username: '',
  password: '',
  repassword: ''
})
// 整个表单校验规则
// 1.非空校验
// 2.长度校验
// 3.正则校验 pattern
// 4.自定义校验
// 注册校验
const Registerrules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'change' },
    { min: 5, max: 10, message: '用户名必须是5~10位', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'change' },
    { pattern: /^\S{6,15}$/, message: '密码必须是6~15位非空', trigger: 'blur' }
  ],
  repassword: [
    { required: true, message: '请重新输入密码', trigger: 'blur' },
    { pattern: /^\S{6,15}$/, message: '密码必须是6~15位非空', trigger: 'blur' },
    {
      validate: (rules, value, callback) => {
        if (value !== rulesForm.value.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
// 登录校验
const Loginrules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'change' },
    { min: 5, max: 10, message: '用户名必须是5~10位', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'change' },
    { pattern: /^\S{6,15}$/, message: '密码必须是6~15位非空', trigger: 'blur' }
  ]
}
// 但我们发现一个问题，在来回切换页面的时候，输入框的值会带入
// 为此我们添加监视，重置表单
watch(isRegister, () => {
  rulesForm.value = {
    username: '',
    password: '',
    repassword: ''
  }
})
// 这是在注册之前的预校验
const register = async () => {
  await form.value.validate()
  await userRegisterService(rulesForm.value)
  ElMessage('注册成功')
  isRegister.value = false
}
const userStore = useUserStore()
// code: 0 → 请求成功
// code: 1 → 请求失败（业务逻辑错误）
// code: 401 → 未授权（token无效或过期）
const login = async () => {
  // 先获取到输入框的数据后校验
  await form.value.validate()
  // 发起请求
  const res = await userLogin(rulesForm.value)
  // 存入新用户
  userStore.setToken(res.data.token)
  ElMessage.success('登录成功')
  console.log('登录参数:', res.data.token)
  router.push('/')
}
</script>
<template>
  <el-row class="login_page">
    <el-col :span="12" class="bg_one"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <el-form
        size="large"
        autocomplete="off"
        v-if="isRegister"
        :model="rulesForm"
        :rules="Loginrules"
        ref="form"
      >
        <el-form-item>
          <h1 class="title">登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            :prefix-icon="User"
            v-model="rulesForm.username"
            placeholder="请输入用户名"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            :prefix-icon="Lock"
            v-model="rulesForm.password"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码?</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" auto-insert-space @click="login"
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link
            type="info"
            class="flex"
            :underline="false"
            @click="isRegister = false"
            >注册 →</el-link
          >
        </el-form-item>
      </el-form>
      <el-form
        size="large"
        autocomplete="off"
        :model="rulesForm"
        :rules="Registerrules"
        ref="form"
        v-else
      >
        <el-form-item>
          <h1 class="title">注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            :prefix-icon="User"
            v-model="rulesForm.username"
            placeholder="请输入用户名"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            :prefix-icon="Lock"
            v-model="rulesForm.password"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
            :prefix-icon="Lock"
            v-model="rulesForm.repassword"
            type="password"
            placeholder="请再次输入密码"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" auto-insert-space @click="register"
            >注册</el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link
            type="info"
            class="flex"
            :underline="false"
            @click="isRegister = true"
          >
            ← 返回</el-link
          >
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login_page {
  height: 100vh;
  background-color: #fff;

  .bg_one {
    height: 100%;
    /* 新增：确保背景图能显示 */
    background:
      url('@/assets/LOGO.png') no-repeat 60% center / 240px auto,
      url('@/assets/NewsBack.png') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      justify-content: start;
    }

    button {
      width: 100%;
    }

    .flex {
      display: flex;
      flex-direction: row;
      width: 100%;
      justify-content: space-between;
    }
  }
}
</style>
